package vip.wangwenhao.sso.config.security.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import vip.wangwenhao.common.util.RedisUtils;
import vip.wangwenhao.autoconfigure.pojo.UserDetailsPojo;
import vip.wangwenhao.common.enums.RedisKeysEnum;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wangwenhao
 */
@Slf4j
@Component
public class CustomLogoutSuccessHandler
        extends AbstractAuthenticationTargetUrlRequestHandler
        implements LogoutSuccessHandler {


    @Autowired
    @Qualifier("consumerTokenServices")
    private ConsumerTokenServices consumerTokenServices;

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onLogoutSuccess(HttpServletRequest request,
                                HttpServletResponse response,
                                Authentication authentication)
            throws IOException, ServletException {


        if (null != authentication) {
            Object principal = authentication.getPrincipal();

            if (null != principal && principal instanceof UserDetailsPojo) {
                String username = ((UserDetailsPojo) principal).getUsername();
                log.info("{} logout success", username);
                Long userId = ((UserDetailsPojo) principal).getId();

                String sessionRedisKey = RedisKeysEnum.GLOBAL_PRESENT_ORDER_TIME.getKey() + userId;

                Object sessionIdObject = RedisUtils.hGet(sessionRedisKey, "sessionId");
                if (null != sessionIdObject){
                    String redisSessionId = String.valueOf(sessionIdObject);
                    String sessionId = request.getSession().getId();
                    if (sessionId.equals(redisSessionId)) {
                        RedisUtils.delete(sessionRedisKey);
                    }
                }

            }else {
                log.info("{} logout success", principal);
            }
        }

        redirectStrategy.sendRedirect(request, response, "/login");


    }
}